﻿using System;
using System.IO;
using Infrastructure.Common;

namespace Infrastructure
{
    public class SettingsManager<T>
        where T : class ,new()
    {
        #region DataMembers

        private static SettingsManager<T> _instance;
        private readonly string _settingFilePath;
        private static readonly object SyncObject = new object();

        #endregion

        public static SettingsManager<T> Instane
        {
            get
            {
                if (_instance == null)
                {
                    lock (SyncObject)
                    {
                        if (_instance == null)
                        {
                            _instance = new SettingsManager<T>();
                        }
                    }
                }
                return _instance;
            }
        }

        public T Settings { get;  set; }

        private SettingsManager ()
        {
            var settingPath = Path.Combine( Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData ), Path.GetFileNameWithoutExtension( System.AppDomain.CurrentDomain.FriendlyName ) );

            _settingFilePath = Path.Combine( settingPath, typeof( T ).Name + ".xml" );

            if (!Directory.Exists( settingPath ))
            {
                Directory.CreateDirectory( settingPath );
            }

            LoadConfigurations();
            SaveConfigurations();
        }

        public void LoadConfigurations ()
        {
            if (File.Exists( _settingFilePath ))
            {
                using (FileStream stream = File.OpenRead( _settingFilePath ))
                {
                    Settings = SerializationUtils.Deserialize<T>( stream );
                }
            }
            else
            {
                Settings = new T();
            }
        }

        public void SaveConfigurations ()
        {
            byte[] fs = SerializationUtils.Serialize( Settings );
            File.WriteAllBytes( _settingFilePath, fs );
        }
    }
}
